//
//  EmoticonTextView.swift
//  EmojiKeyboard
//
//  Created by ZhangZiang on 15/12/28.
//  Copyright © 2015年 ZhangZiang. All rights reserved.
//

import UIKit

class EmoticonTextView: UITextView {

    //把表情转换成文本
    func fullText() -> String {
        let allText = self.attributedText
        
        var strMu = String()
        
        allText.enumerateAttributesInRange(NSRange(location: 0, length: allText.length), options: []) { (dict, range, _) -> Void in
            //            print(dict)
            //print(range)
            //当有NSAttachment键时候,就说明有新浪表情了
            if let attachment = dict["NSAttachment"] as? EmoticonTextAttachment {
                //                print("有图片")
                strMu += (attachment.chs ?? "")
            } else {
                let str = (self.text as NSString).substringWithRange(range)
                strMu += str
            }
        }
    
        return strMu
    }

    
    func insertEmoticon(em : Emoticon) {
        if em.isEmpty == true {
            print("空表情")
            return
        }
        
        if em.isDelete == true {
            deleteBackward()
            return
        }
        
        //如果是emoji表情
        if em.emojiStr != nil {
            if let textRange = selectedTextRange {
                replaceRange(textRange, withText: em.emojiStr ?? "")
            }
            return
        }
        
        //到这里则是新浪表情
        let imageText = EmoticonTextAttachment().emoticonTextToImageText(em, font : font!)
        
        //先记录开始的光标位置
        let range = selectedRange
        
        //属性替换
        let allText = NSMutableAttributedString(attributedString: attributedText)
        allText.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        attributedText = allText
        
        //恢复到原来的光标位置
        selectedRange = NSMakeRange(range.location + 1, 0)
        
        //发出文本变化的事件
        delegate?.textViewDidChange?(self)
    }

}
